package org.jeecg.modules.villageCadreAssist.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.villageCadreAssist.entity.VcaPensionSupply;
import org.jeecg.modules.villageCadreAssist.entity.VcaResident;
import org.jeecg.modules.villageCadreAssist.service.IVcaPensionSupplyService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.villageCadreAssist.service.IVcaResidentService;
import org.jeecg.modules.villageCadreAssist.util.CommonUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: vca_pension_supply
 * @Author: jeecg-boot
 * @Date:   2022-03-08
 * @Version: V1.0
 */
@Api(tags="vca_pension_supply")
@RestController
@RequestMapping("/villageCadreAssist/vcaPensionSupply")
@Slf4j
public class VcaPensionSupplyController extends JeecgController<VcaPensionSupply, IVcaPensionSupplyService> {
	@Autowired
	private IVcaPensionSupplyService vcaPensionSupplyService;
	@Autowired
	private IVcaResidentService vcaResidentService;

	/**
	 * 分页列表查询
	 *
	 * @param vcaPensionSupply
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "vca_pension_supply-分页列表查询")
	@ApiOperation(value="vca_pension_supply-分页列表查询", notes="vca_pension_supply-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(VcaPensionSupply vcaPensionSupply,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Page<VcaPensionSupply> page = new Page<VcaPensionSupply>(pageNo, pageSize);
		QueryWrapper<VcaPensionSupply> queryWrapper = QueryGenerator.initQueryWrapper(vcaPensionSupply, req.getParameterMap());
		queryWrapper.setEntity(vcaPensionSupply);
		CommonUtil.nameOrLetter(vcaPensionSupply);
		String orgCode = CommonUtil.checkOrgCode(vcaPensionSupply);

		IPage<VcaPensionSupply> pageList = vcaPensionSupplyService.queryPageList(page, queryWrapper,orgCode);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param vcaPensionSupply
	 * @return
	 */
	@AutoLog(value = "vca_pension_supply-添加")
	@ApiOperation(value="vca_pension_supply-添加", notes="vca_pension_supply-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody VcaPensionSupply vcaPensionSupply) {
		vcaPensionSupplyService.save(vcaPensionSupply);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param vcaPensionSupply
	 * @return
	 */
	@AutoLog(value = "vca_pension_supply-编辑")
	@ApiOperation(value="vca_pension_supply-编辑", notes="vca_pension_supply-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody VcaPensionSupply vcaPensionSupply) {
		vcaPensionSupplyService.updateById(vcaPensionSupply);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "vca_pension_supply-通过id删除")
	@ApiOperation(value="vca_pension_supply-通过id删除", notes="vca_pension_supply-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		vcaPensionSupplyService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "vca_pension_supply-批量删除")
	@ApiOperation(value="vca_pension_supply-批量删除", notes="vca_pension_supply-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.vcaPensionSupplyService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "vca_pension_supply-通过id查询")
	@ApiOperation(value="vca_pension_supply-通过id查询", notes="vca_pension_supply-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		VcaPensionSupply vcaPensionSupply = vcaPensionSupplyService.getById(id);
		if(vcaPensionSupply==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(vcaPensionSupply);
	}

	 @AutoLog(value = "vca_pension_supply-通过pensionSupply查询")
	 @ApiOperation(value="vca_pension_supply-通过pensionSupply查询", notes="vca_pension_supply-通过pensionSupply查询")
	 @GetMapping(value = "/queryPensionSupply")
	 public Result<?> queryPensionSupply(VcaPensionSupply pensionSupply) {
		 VcaPensionSupply vcaPensionSupply = vcaPensionSupplyService.getOne(new QueryWrapper<VcaPensionSupply>().setEntity(pensionSupply));

		 if(vcaPensionSupply==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(vcaPensionSupply);
	 }
    /**
    * 导出excel
    *
    * @param request
    * @param vcaPensionSupply
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, VcaPensionSupply vcaPensionSupply) {
        return super.exportXls(request, vcaPensionSupply, VcaPensionSupply.class, "vca_pension_supply");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		//TODO  以后修改为批量处理
		List<VcaPensionSupply> vcaPensionSupplies = this.importExcel(request, VcaPensionSupply.class);
		List<String> idcardList = vcaPensionSupplies.stream().map(item -> item.getIdcard()).collect(Collectors.toList());
		List<VcaResident> list = vcaResidentService.list(new LambdaQueryWrapper<VcaResident>().in(VcaResident::getIdcard, idcardList));

		Map<String, Integer> map = list.stream().collect(Collectors.toMap(VcaResident::getIdcard, VcaResident::getId));
		List<String> errorIdcards = new ArrayList<>();

		Iterator<VcaPensionSupply> iterator = vcaPensionSupplies.iterator();
		while(iterator.hasNext()){
			VcaPensionSupply next = iterator.next();
			Integer residentId = map.get(next.getIdcard());
			if(residentId==null){
				errorIdcards.add(next.getIdcard());
				iterator.remove();
			}else{
				String level = next.getLevel();
				String[] levelMoney = level.split("-");
				next.setLevel(levelMoney[0]);
				next.setMoney(Integer.parseInt(levelMoney[1]));
				String idcard = next.getIdcard();
				next.setYear(Integer.parseInt(idcard.substring(6,10))+60);
				next.setStatus(1);
				next.setMonth(Integer.parseInt(idcard.substring(10,12)));
				next.setResidentId(residentId);
			}
		}
		if(errorIdcards.size()>0){
			return Result.error("身份证号为："+errorIdcards+"的居民不在系统内，请确认身份证是否正确");
		}
		vcaPensionSupplyService.saveBatch(vcaPensionSupplies);

		return Result.OK("导入成功");
	}

	 protected List<VcaPensionSupply> importExcel(HttpServletRequest request, Class<VcaPensionSupply> clazz) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 List allList = new ArrayList<>();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(0);
			 params.setHeadRows(1);
			 params.setNeedSave(false);
			 try {
				 allList.addAll(ExcelImportUtil.importExcel(file.getInputStream(), clazz, params));
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 throw new RuntimeException("导入异常："+e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return allList;
	 }


}
